<?php
namespace app\user\home;

use app\common\controller\Common;
use thans\jwt\facade\JWTAuth;
use Naixiaoxin\ThinkWechat\Facade;
use app\rocky\model\User as UserModel;

/**
 * 前台首页控制器
 * @package app\cms\admin
 */
class Wechat extends Common
{

    // 定义服务端服务
    protected $official;
    protected $oauth;

    /**
     * 初始化方法
     */
    protected function initialize()
    {
        parent::initialize();

        //初始化实例
        $this->official = Facade::officialAccount();
        $this->oauth = $this->official->oauth;
    }

    // 网页跳转授权
    public function oauth()
    {
        $url = input('get.url/s',null);
        if(!$url) jerror('跳转链接错误');

        if (empty(session('wechat_user'))){
            session('target_url', $url);
            //$callback_url = request()->domain().url('user/wechat/callback');
            $redirect_url = $this->oauth->scopes(['snsapi_userinfo'])->redirect();
            header("Location:".$redirect_url);exit;
        }else{
            //获取TOKEN 跳转
            $user_info = UserModel::addUser(session('wechat_user'));
            $token = JWTAuth::builder(['id' => $user_info['id']]);
            $target_url = add_querystring_var($url, 'token', $token);

            header("Location:".$target_url);exit;
        }
    }

    // 网页授权回调
    public function callback()
    {
        $target_url = session('target_url');

        # 获取用户信息
        $code = input('get.code/s',null);
        if(!$code) jerror("参数错误");

        $user_info = $this->oauth->userFromCode($code);

        # session存储用户信息
        session('wechat_user', $user_info);

        //获取TOKEN 跳转
        $info = UserModel::addUser($user_info);
        $token = JWTAuth::builder(['id' => $info['id']]);
        $target_url = add_querystring_var($target_url, 'token', $token);

        header("Location:".$target_url);exit;
    }

    // JDK分享
    public function share()
    {
        //分享
        $url = input('get.url/s','');
        $url = $url ? $url : request()->url(true);

        $this->official->jssdk->setUrl($url);
        $config = $this->official->jssdk->buildConfig([
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'hideMenuItems',
            'startRecord',
            'stopRecord',
            'playVoice',
            'onVoiceRecordEnd',
            'uploadVoice',
            'onVoicePlayEnd',
            'downloadVoice',
            'getLocation',
            'chooseWXPay'
        ]);

        jsuccess($config);
    }
}